package com.dsl.dslsuzhou.controller;

import com.dsl.dslsuzhou.model.dto.*;
import com.dsl.dslsuzhou.service.CameraService;
import com.dsl.dslsuzhou.service.CameraCountOptimizedService;
import com.dsl.dslsuzhou.service.CameraPageOptimizedService;
import com.dsl.dslsuzhou.service.DeviceService;
import com.dsl.dslsuzhou.service.ZljLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * 摄像头接口控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/${api-module}/cameras")
public class CameraController {

    @Autowired
    private CameraService cameraService;

    @Autowired
    private CameraCountOptimizedService cameraCountOptimizedService;

    @Autowired
    private CameraPageOptimizedService cameraPageOptimizedService;

    @Resource
    private ZljLoginService zljLoginService;

    @Resource
    private DeviceService deviceService;

    /**
     * 分页查询摄像头（兼容性优化版本）
     * 支持两种调用方式：
     * 1. 兼容模式：GET /cameras/page?devIds=CAM001,CAM002&current=1&size=10&status=1
     * 2. 优化模式：GET /cameras/page?category=视频监控&area=东区&current=1&size=10&status=1
     */
    @GetMapping("/page")
    public Mono<ResponseEntity<ApiResponse<CameraPageResponse>>> getCameraPage(
            @RequestParam(required = false) Integer current,
            @RequestParam(required = false) Integer size,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String area,
            @RequestParam(required = false) String building,
            @RequestParam(required = false) String floor) {

        try {
            // 参数默认值处理
            Integer finalCurrent = (current != null && current > 0) ? current : 1;
            Integer finalSize = (size != null && size > 0) ? size : 5;

            // 获取token
            String token = zljLoginService.getZljToken();

            // 使用优化服务进行分页查询
            return cameraPageOptimizedService.getCameraPageOptimized(StringUtils.hasText(category) ? category : "通用视频服务设备", area, building, floor,
                            finalCurrent, finalSize, status, token)
                    .map(response -> ResponseEntity.ok(ApiResponse.success(response)))
                    .onErrorResume(this::handleError);

        } catch (Exception e) {
            log.error("摄像头分页查询参数错误", e);
            return Mono.just(ResponseEntity.badRequest()
                    .body(ApiResponse.badRequest(e.getMessage())));
        }
    }

    /**
     * 统计摄像头数量（性能优化版本）
     * GET /cameras/count?category=视频监控&area=东区&building=A栋&floor=3F&status=1
     * 支持按设备条件统计，内置分批处理、缓存、并发控制等优化
     */
    @GetMapping("/count")
    public Mono<ResponseEntity<ApiResponse<CameraCountResponse>>> getCameraCount(
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String area,
            @RequestParam(required = false) String building,
            @RequestParam(required = false) String floor,
            @RequestParam(required = false) Integer status) {

        try {
            log.info("接收摄像头统计请求: category={}, area={}, building={}, floor={}, status={}",
                    category, area, building, floor, status);

            // 获取token
            String token = zljLoginService.getZljToken();
            log.info("token: {}", token);

            // 使用优化服务进行统计
            return cameraCountOptimizedService.countCamerasByConditions(
                            StringUtils.hasText(category) ? category : "通用视频服务设备",
                            area, building, floor, status, token)
                    .map(response -> ResponseEntity.ok(ApiResponse.success(response)))
                    .onErrorResume(this::handleError);

        } catch (Exception e) {
            log.error("摄像头统计请求参数错误", e);
            return Mono.just(ResponseEntity.badRequest()
                    .body(ApiResponse.badRequest(e.getMessage())));
        }
    }

    /**
     * 统一异常处理
     */
    private <T> Mono<ResponseEntity<ApiResponse<T>>> handleError(Throwable throwable) {
        log.error("摄像头接口调用异常", throwable);

        if (throwable instanceof IllegalArgumentException) {
            // 参数错误
            return Mono.just(ResponseEntity.badRequest()
                    .body(ApiResponse.badRequest(throwable.getMessage())));
        } else if (throwable instanceof TimeoutException) {
            // 超时错误
            return Mono.just(ResponseEntity.status(HttpStatus.GATEWAY_TIMEOUT)
                    .body(ApiResponse.timeout()));
        } else if (throwable.getMessage() != null && throwable.getMessage().contains("401")) {
            // 未授权
            return Mono.just(ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.unauthorized()));
        } else {
            // 第三方服务错误
            return Mono.just(ResponseEntity.status(HttpStatus.BAD_GATEWAY)
                    .body(ApiResponse.thirdPartyError()));
        }
    }
}
